<?php
/**
 *
 * 版权所有：恰维网络<qwadmin.qiawei.com>
 * 作    者：寒川<hanchuan@qiawei.com>
 * 日    期：2016-01-17
 * 版    本：1.0.0
 * 功能说明：后台登录控制器。
 *
 **/

namespace Admin\Controller;

use Think\Controller;

class LoginController extends Controller
{
    public function index()
    {
        if($_SESSION['uid']){

            $url = U('index/index');
            header("Location: $url");
        }

        $this->display();
    }

    public function login()
    {
        $verify = isset($_POST['verify']) ? trim($_POST['verify']) : '';
        if (!$this->check_verify($verify, 'login')) {
            $this->error('验证码错误！', U("login/index"));
        }

        $username = isset($_POST['user']) ? trim($_POST['user']) : ''; 
        $password = isset($_POST['password']) ? md5(trim($_POST['password'])) : '';
        if ($username == '') {
            $this->error('用户名不能为空！', U("login/index"));
        } elseif ($password == '') {
            $this->error('密码必须！', U("login/index"));
        }
        $model = M("Administrator");
        $user = $model->field('id,username')->where(array('username' => $username, 'pwd' => $password))->find();

        if ($user) {
            session('uid',$user['id']);
            session('username',$user['username']);
            $data['last_login_time'] = date("Y-m-d H:i:s");
            $model->where('id='.$user['id'])->data($data)->save();
            echo "<script>alert('登录成功！')</script>";
            $url = U('index/index');
            header("Location: $url");
            exit(0);
        } else {
            $this->error('登录失败，请重试！', U("login/index"));
        }
    }

    function check_verify($code, $id = '')
    {
        $verify = new \Think\Verify();
        return $verify->check($code, $id);
    }

    public function verify()
    {
        $config = array(
            'fontSize' => 15, // 验证码字体大小
            'length' => 2, // 验证码位数
            'useNoise' => false, // 关闭验证码杂点
            'imageW' => 100,
            'imageH' => 30,
        );
        $verify = new \Think\Verify($config);
        $verify->entry('login');
    }

    public function loginout(){

        $_SESSION = array();
        $url = U('Login/index');
        header("Location: $url");

    }

}
